from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from rest_framework import mixins, viewsets
from rest_framework.permissions import IsAuthenticated
from utils.permissions import IsOwnerOrReadOnly
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.authentication import SessionAuthentication
from .serializers import *
from .models import *


# 购物车视图类
class ShoppingCartViewset(ModelViewSet):
    """
    购物车功能
    list:
        获取购物车详情
    create：
        加入购物车
    delete：
        删除购物记录
    """
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    lookup_field = 'goods_id'

    # serializer_class = ShoppingCartSerializer
    def get_serializer_class(self):
        if self.action == 'list':
            return ShoppingCartDetailSerializer
        return ShoppingCartSerializer

    # 返回当前用户的购物车列表
    def get_queryset(self):
        return ShoppingCart.objects.filter(user=self.request.user)


# 订单视图类
class OrderViewset(mixins.ListModelMixin,
                   mixins.CreateModelMixin,
                   mixins.RetrieveModelMixin,
                   mixins.DestroyModelMixin,
                   viewsets.GenericViewSet):

    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    # serializer_class = OrderSerializer
    # 动态获取序列化对象
    def get_serializer_class(self):
        if self.action == 'retrieve':
            return OrderDetailSerializer
        return OrderSerializer

    def get_queryset(self):
        return OrderInfo.objects.filter(user=self.request.user)

    # 创建订单：生成订单，清空购物车
    def perform_create(self, serializer):
        order = serializer.save()
        shop_carts = ShoppingCart.objects.filter(user=self.request.user)

        # 把购物车中的商品记录存入订单详情表
        for shop_cart in shop_carts:
            order_goods = OrderGoods()
            order_goods.goods = shop_cart.goods
            order_goods.goods_num = shop_cart.nums
            order_goods.order = order
            order_goods.save()

            # 保存到订单详情表后，从购物车表中删除
            shop_cart.delete()
        return order


from rest_framework.views import APIView
from utils.alipay import AliPay
from SxShop3.settings import ali_pub_key_path, private_key_path
from rest_framework.response import Response
from django.shortcuts import redirect, reverse


# 支付宝接口
# 没有模型，用基础APIView类
class AlipayView(APIView):

    # 处理支付宝的return_url返回
    def get(self, request):
        processed_dict = {}
        for key, value in request.GET.items():
            # django的POST里直接就是value
            processed_dict[key] = value
        sign = processed_dict.pop('sign', None)

        alipay = AliPay(
            appid="2016082600314022",
            # 异步处理：网页支付未确认，去手机端支付; 修改订单状态===POST请求
            # 电脑网站支付结果异步通知
            app_notify_url="http://127.0.0.1:8000/alipay/return/",
            app_private_key_path=private_key_path,
            alipay_public_key_path=ali_pub_key_path,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            debug=True,  # 默认False,
            return_url="http://127.0.0.1:8000/alipay/return/"
        )

        # 验证支付宝返回的数据是否正确
        ret = alipay.verify(processed_dict, sign)
        print(ret, '==========')
        if ret is True:
            order_sn = processed_dict.get('out_trade_no', None)
            trade_no = processed_dict.get('trade_no', None)
            trade_status = processed_dict.get('trade_status', None)
            # ????????????????
            print(order_sn, trade_no, trade_status, '==========333')

            orders = OrderInfo.objects.filter(order_sn=order_sn)
            order = orders[0]
            order.pay_status = 'TRADE_SUCCESS'
            order.trade_no = trade_no
            order.pay_time = datetime.now()
            order.save()
            # # 给支付宝返回success，不然支付宝会重复访问alipay/return
            # return Response('success')
            response = redirect('index')
            response.set_cookie('nextPath', 'pay', max_age=2)
            return response
        else:
            return redirect('index')

    # 处理支付宝的notify_url返回
    def post(self, request):
        processed_dict = {}
        for key, value in request.POST.items():
            # django的POST里直接就是value
            processed_dict[key] = value
        sign = processed_dict.pop('sign', None)

        alipay = AliPay(
            appid="2016082600314022",
            # 异步处理：网页支付未确认，去手机端支付; 修改订单状态===POST请求
            # 电脑网站支付结果异步通知
            app_notify_url="http://127.0.0.1:8000/alipay/return/",
            app_private_key_path=private_key_path,
            alipay_public_key_path=ali_pub_key_path,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            debug=True,  # 默认False,
            return_url="http://127.0.0.1:8000/alipay/return/"
        )

        # 验证支付宝返回的数据是否正确
        ret = alipay.verify(processed_dict, sign)
        print(ret, '==========')
        if ret is True:
            order_sn = processed_dict.get('out_trade_no', None)
            trade_no = processed_dict.get('trade_no', None)
            trade_status = processed_dict.get('trade_status', None)

            orders = OrderInfo.objects.filter(order_sn=order_sn)
            order = orders[0]
            order.pay_status = trade_status
            order.trade_no = trade_no
            order.pay_time = datetime.now()
            order.save()
            # 给支付宝返回success，不然支付宝会重复访问alipay/return
            return Response('success')






